package com.tjakus.arduino.serial;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import com.tjakus.arduino.encoder.CommandEncoder;
import com.tjakus.arduino.logging.Logging;

public class ArduinoCommunicator implements SerialPortEventListener {

	// The port which will be used
	private static SerialPort serialPort;
	// Type of ports for Mac, Linux and Windows
	private static final String PORT_NAMES[] = { "/dev/tty.usbserial-A9007UX1", // MacOS
			"/dev/ttyUSB0", // Linux
			"COM7" }; // Windows
	// Buffered input stream from the port
	private static InputStream input;
	// The output stream to the port
	private static OutputStream output;
	// Milliseconds to block while waiting for port open
	private static final int TIME_OUT = 2000;
	// Default bits per second for COM port.
	private static final int DATA_RATE = 9600;
	private static String inputBuffer = "";

	public static boolean initialize() {
		Logging.getLogger().info(
				"ArduinoCommunicator - initialize [ ]");
		CommPortIdentifier portId = null;
		@SuppressWarnings("rawtypes")
		Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

		// Iterate through port types, looking for the port
		while (portEnum.hasMoreElements()) {
			CommPortIdentifier currPortId = (CommPortIdentifier) portEnum
					.nextElement();
			for (String portName : PORT_NAMES) {
				if (currPortId.getName().equals(portName)) {
					portId = currPortId;
					break;
				}
			}
		}

		if (portId == null) {
			Logging.getLogger().error(
					"ArduinoCommunicator - initialize [ Unable to find serial port ]");
			return false;
		} else {
			Logging.getLogger().info(
					"ArduinoCommunicator - initialize - port [ " + portId + " ]");
		}

		try {
			// open serial port, and use class name for the appName.
			serialPort = (SerialPort) portId
					.open(ArduinoCommunicator.class.getName(), TIME_OUT);

			// set port parameters
			serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

			// open the streams
			input = serialPort.getInputStream();
			output = serialPort.getOutputStream();

			// add event listeners
			serialPort.addEventListener(new ArduinoCommunicator());
			serialPort.notifyOnDataAvailable(true);

		} catch (Exception e) {
			Logging.getLogger().error(
					"ArduinoCommunicator - initialize [ Communication error ]", e);
			return false;
		}
		return true;
	}

	/**
	 * This Method is called to send a String to the Arduino over serial
	 * connection
	 */
	public static synchronized void sendToArduino(String msg) {
		try {
			// add a newline character at the end
			msg += '\n';
			// write it to the serial
			output.write(msg.getBytes());
			// refresh the serial
			output.flush();
			Logging.getLogger().info("ArduinoCommunicator - sendToArduino [ " + msg + " ]");
		} catch (Exception e) {
			Logging.getLogger().error(
					"ArduinoCommunicator - sendToArduino [ Unable to send ]", e);
		}
	}

	/**
	 * This Method is called when Serial data is received
	 */
	public synchronized void serialEvent(SerialPortEvent oEvent) {
		if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
			try {
				int available = input.available();
				// read all incoming characters
				for (int i = 0; i < available; i++) {
					// store it into an int because of the input.read method
					int receivedVal = input.read();
					// if the character is not a new line "\n" and not a carriage return
					if (receivedVal != 10 && receivedVal != 13) {
						// store the new character into a buffer
						inputBuffer += (char) receivedVal;
						// if it's a new line character
					} else if (receivedVal == 10) {
						Logging.getLogger().info(
								"ArduinoCommunicator - serialEvent [ " + inputBuffer + " ]");
						// call the method to encode the received command
						CommandEncoder.encodeCommand(inputBuffer);
						// clear the buffer
						inputBuffer = "";
					}
				}
			} catch (Exception e) {
				Logging.getLogger().error(
						"ArduinoCommunicator - serialEvent [ Unable to receive ]", e);
			}
		}
	}

	/**
	 * This should be called when you stop using the port. This will prevent port
	 * locking on platforms like Linux.
	 */
	public static synchronized void close() {
		if (serialPort != null) {
			serialPort.removeEventListener();
			serialPort.close();
		}
	}
}
